package org.pblue.appengine.frontend.view;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.pblue.appengine.frontend.model.Configuration;


@SuppressWarnings("serial")
public abstract class View extends HttpServlet {
  
  public static final String REQUEST_ATTRIBUTE_CONFIGURATION = "config";
  public static final String REQUEST_ATTRIBUTE_MESSAGE = "message";
  
  protected String mTemplate;
  protected String mErrorTemplate;
  protected Configuration mConfiguration;
  
  public abstract void process(HttpServletRequest pRequest, HttpServletResponse pResponse) throws ServletException, IOException;

  @Override
  protected void service(HttpServletRequest pRequest, HttpServletResponse pResponse) throws ServletException, IOException {
    this.process(pRequest, pResponse);
  }
  
  protected void forward(HttpServletRequest pRequest, HttpServletResponse pResponse) throws ServletException, IOException {
    pRequest.setAttribute(REQUEST_ATTRIBUTE_CONFIGURATION, this.getConfiguration());
    RequestDispatcher rd = pRequest.getRequestDispatcher(this.getTemplate());
    rd.forward(pRequest, pResponse);
  }
  
  protected void error(HttpServletRequest pRequest, HttpServletResponse pResponse, String pMessage) throws ServletException, IOException {
    pRequest.setAttribute(REQUEST_ATTRIBUTE_CONFIGURATION, this.getConfiguration());
    pRequest.setAttribute(REQUEST_ATTRIBUTE_MESSAGE, pMessage);
    RequestDispatcher rd = pRequest.getRequestDispatcher(this.getErrorTemplate());
    rd.forward(pRequest, pResponse);
  }
  
  public String getTemplate() {
    return mTemplate;
  }
  
  public void setTemplate(String pTemplate) {
    mTemplate = pTemplate;
  }
  
  public String getErrorTemplate() {
    return mErrorTemplate;
  }
  
  public void setErrorTemplate(String pErrorTemplate) {
    mErrorTemplate = pErrorTemplate;
  }
  
  public Configuration getConfiguration() {
    return mConfiguration;
  }
  
  public void setConfiguration(Configuration pConfiguration) {
    mConfiguration = pConfiguration;
  }

}